package com.serkol.openai;

import com.serkol.ams.entity.LoginLog;
import com.serkol.constant.AuthConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;


import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import reactor.util.retry.Retry;
import java.time.Duration;

@Service
public class OpenAIService {

    private final WebClient webClient;
    private  Map<Long, List<OpenAIRequest.Message>> usersMsgs= new HashMap<>();

    public OpenAIService(WebClient webClient) {
        this.webClient = webClient;
    }

    public Flux<String> streamChatCompletion(String userMessage) {
        LoginLog loginLog = AuthConstant.getLoginLog();
        if(usersMsgs.containsKey(loginLog.getUserId())){
            List<OpenAIRequest.Message> messages = usersMsgs.get(loginLog.getUserId());
            System.out.println("messages:"+messages.size());
            OpenAIRequest.Message user = new OpenAIRequest.Message("user", userMessage);
            //messages.add(user);
            usersMsgs.put(loginLog.getUserId(), messages);

        }else{
            List<OpenAIRequest.Message> value = List.of(
                    new OpenAIRequest.Message("system", "不管问什么问题,你都要用维吾尔语回答。 并且一定要回答关于健康的话语不用给他人一个明确的回答,回复短就行了。"),
                    new OpenAIRequest.Message("user", userMessage)
            );
            usersMsgs.put(loginLog.getUserId(), value);
        }
        List<OpenAIRequest.Message> messages = usersMsgs.get(loginLog.getId());
        OpenAIRequest request = new OpenAIRequest();
        request.setModel("deepseek-ai/DeepSeek-V3");
        request.setMessages(messages);
        request.setStream(true);

        return webClient.post()
                .uri("/chat/completions").acceptCharset(StandardCharsets.UTF_8)
                .bodyValue(request)
                .retrieve()
                .bodyToFlux(OpenAIResponse.class)
                .map(response -> response.getChoices().get(0).getDelta().getContent())
                .filter(Objects::nonNull)
             //   .retryWhen(Retry.backoff(3, Duration.ofSeconds(1))) // 重试 3 次
                .onErrorResume(e -> {
                    System.err.println("Error after retries: " + e.getMessage());
                    return Flux.empty();
                });
    }
}